package com.example.orderfood2;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.orderfood2.DatabaseManager.DatabaseManager;
import com.example.orderfood2.Repository.SchoolNewRepository;

public class AddSchoolNew extends AppCompatActivity {
    private CardView successCard;
    private EditText titleEditText, contentEditText;
    private Button publishButton,cancelButton;
    SchoolNewRepository schoolNewRepository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        schoolNewRepository = DatabaseManager.getInstance(this).getSchoolNewRepository();
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_add_school_new);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
//        加载视图
        setContentView(R.layout.activity_add_school_new);
        // 初始化视图
        successCard = findViewById(R.id.successCard);
        titleEditText = findViewById(R.id.titleEditText);
        contentEditText = findViewById(R.id.contentEditText);
        publishButton = findViewById(R.id.publishButton);
        cancelButton = findViewById(R.id.cancel_button);
        cancelButton.setOnClickListener(v -> finish());
        publishButton.setOnClickListener(v -> publishNew());
    }

    private void publishNew() {
        String title = titleEditText.getText().toString().trim();
        String content = contentEditText.getText().toString().trim();
        // 验证输入
        if (title.isEmpty() || content.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }
        schoolNewRepository.addSchoolNew(title, content);
        showSuccessMessage();
        clearForm();
    }
    private void showSuccessMessage() {
        // 显示成功提示
        successCard.setVisibility(View.VISIBLE);

        // 3秒后自动隐藏
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            successCard.setVisibility(View.GONE);
        }, 3000);
    }
    private void clearForm() {
        titleEditText.setText("");
        contentEditText.setText("");
    }
}